Ext.onReady(function() {

    Ext.QuickTips.init();// 浮动信息提示

    //树状结构
    var treePanel = new Ext.tree.TreePanel({
        el : 'tree-panel',// 将树形添加到一个指定的div中,非常重要！
        title : '人员管理工作台',
        width :200,
        height : 480,
        split : true,
        lines:true,
        autoHeight : false,
        containerScroll : true,// 是否支持滚动条
        rootVisible : true, // 是否隐藏根节点,很多情况下，我们选择隐藏根节点增加美观性
        collapsible:false,
        collapsed:false,
        collapseFirst:true,
        titleCollapse:true,
        border : false,
        //align: left,
        //border : true, // 边框

        animate : true, // 动画效果

        loader : loader,
            // 树加载
        listeners:{ 
        	render:function(tree){ 
        		treePanel.el.on('click',function(e){ 
				e.stopPropagation(); }) ;
			} 
		} 

        });

var loader=new Ext.tree.TreeLoader({dataUrl:'system/showOrgTree.do'});

var treeRoot=new Ext.tree.AsyncTreeNode
    ({
     id:"0", 
     leaf:false,
     loader: loader,
     text:"清远农商行总行",
     expandable:true,
     expanded:true 
 });         

treePanel.setRootNode(treeRoot);
treePanel.render();

var treeClick = function(node,e)
    {
	 var flag = false; 
	  if(node.attributes.leaf)
      {
          if(node.isLeaf())
          {
        	  e.stopEvent();
        	  flag = true;
          }
         
      }
		Ext.Ajax.request({
			url:'system/loadUserTreeFromParent.do',
			params : { orgId: node.id, isLeaf: flag},
			method:'POST',
			   success:function(response){
				   grid.store.reload(); 
				   treePanel.root.reload();
			  },failure:function(){
			    Ext.MessageBox.alert("请求异常！");
			  }
			});
      
    };
treePanel.on("click",treeClick); 
	

	//机构列表
    
	var record_start = 0; 
	var sm = new Ext.grid.CheckboxSelectionModel();
	var cm=new Ext.grid.ColumnModel([ 
	sm,
	new Ext.grid.RowNumberer({header: "编号",
	width:40, 
	renderer:function(value,metadata,record,rowIndex){ 
	return record_start + 1 + rowIndex; 
	} 
	}),
	{header:'人员编号',dataIndex:'userId',width:120},
	{header:'人员名称',dataIndex:'username',width:120},
	{header:'登录名',dataIndex:'loginid',width:100},
	{header:'所属机构',dataIndex:'belongorgName',width:100},
	{header:'所属部门',dataIndex:'belongdept',width:100},
	{header:'办公电话',dataIndex:'companytel',width:100},
	{header:'移动电话',dataIndex:'mobiletel',width:100},
	{header:'Email',dataIndex:'email',width:100},
	{header:'更新日期',dataIndex:'updateDate',width:100},
	]); 
	var ds=new Ext.data.Store({ 
	proxy:new Ext.data.HttpProxy({
	url:'system/listUser.do',
	method:'POST'
	}), 
	reader:new Ext.data.JsonReader({ 
	totalProperty:'total',  
	root:'resultData'},[
	{name:'userId'}, 
	{name:'username'}, 
	{name:'loginid'},   
	{name:'belongorgName'},
	{name:'belongdept'},
	{name:'companytel'},
	{name:'mobiletel'},
	{name:'email'},
	{name:'updateDate'},
	]) 
	});

	var conditionStore = new Ext.data.SimpleStore({
		   fields : ['id', 'text'],
		   data : [['userId', '人员编号'], ['userName', '人员名称']]
	});
	
	var grid=new Ext.grid.GridPanel({ 
		id:'myCustomers',
		renderTo:"list", 
		stripeRows:true,//斑马线效果
		title:"人员列表", 
		height:500, 
		cm:cm,
		store: ds, 
		loadMask: { msg: "加载中..." }, 
		viewConfig: {   
		                            forceFit:true   
		            },   
		            bbar: new Ext.PagingToolbar({   
		                pageSize: 20,   
		                store: ds,   
		                displayInfo: true,   
		                displayMsg: '第{0} 到 {1} 条数据 共{2}条',   
		                emptyMsg: "没有数据" ,
		                doLoad : function(start){ 
		   record_start = start; 
		var o = {}, pn = this.getParams(); 
		          o[pn.start] = start; 
		          o[pn.limit] = this.pageSize; 
		this.store.load({params:o}); 
		     }  
		            }),
		 tbar: [
		 {text:'新增',handler: startPD},
		 '-',
		 {text:'查看/编辑',handler: PDDetail},
		 '-',
		 {text:'删除',handler: deleteOrg},
		 '-',
		 {text:'密码初始化',handler: initPassword},
		 '-',
		 {text:'关联角色',handler: associateRole},
		 '-',
		 {text:'业务移交',handler: transfer},
		 '->',
	        {xtype:'combo',
	        id:'condition',
	        name: 'condition', 
	        store: conditionStore,
	        fieldLabel: '请选择查询条件',
	        valueField : 'id',
	        displayField : 'text',
	        emptyText : '请选择查询条件',
	        triggerAction : 'all',
	        editable: false,
	        mode:'local',
	        width:110
	        },'',
	        {xtype:'textfield',id:'keyword',width:180},
	        {text:'查询',handler:findCustomer},
	        '-',
	        {text:'清空',handler: callBack} ]              
		});
		ds.load({params:{start:0,limit:20}}); 
		
		

		function findCustomer(){

		var condition = Ext.getCmp('condition').getValue();
		var keyword = Ext.getCmp('keyword').getValue();

		if(condition == '' || condition == null){
			Ext.Msg.alert('提示', '请选择查询条件！'); 
		}
		else{

			ds.baseParams={condition:condition, keyword: keyword};
			ds.proxy = new Ext.data.HttpProxy({
							url:'system/findUser.do',
							method:'POST'
						}); 
			ds.reader = new Ext.data.JsonReader({ 
								totalProperty:'total',  
								root:'resultData'},[
								                    
									{name:'userId', mapping: 'userId'}, 
									{name:'username', mapping: 'username'}, 
									{name:'loginid', mapping: 'loginid'},   
									{name:'belongorgName', mapping: 'belongorgName'},
									{name:'belongdept', mapping: 'belongdept'},
									{name:'companytel', mapping: 'companytel'},
									{name:'mobiletel', mapping: 'mobiletel'},
									{name:'email', mapping: 'email'},
									{name:'updateDate', mapping: 'updateDate'},

							]);
							   
			ds.load({params:{start:0,limit:20}});
			record_start = 0;  	
		}
		}

		function callBack(){
			Ext.getCmp('condition').clearValue();
			Ext.getCmp('keyword').setValue('');
		}
		
		

		//新增客户表单
		addForm = new Ext.form.FormPanel({ 
		id: 'addForm', 
		width: 480, 
		height: 250, 
		//样式 
		bodyStyle: 'margin:auto;padding:auto;', 
		frame: true, 
		xtype: 'filedset', 
		labelWidth: 100, 
		items: 
		[ { xtype: 'fieldset',  
		collapsible: true, 
		autoHeight: true, 
		autoWidth: true, 
		items: 
		[ 
		{ layout : "form",
		           items : [{
		        	   xtype: 'textfield',
		        	   id: 'username', 
		        	   name: 'username', 
		        	   fieldLabel: '人员名称',
		        	   allowBlank : false,
		        	   blankText:'人员名称',
		        	   width: 250
		}]},
		{ layout : "form",
	           items : [{
	        	   xtype: 'textfield',
	        	   id: 'loginid', 
	        	   name: 'loginid', 
	        	   fieldLabel: '登录名',
	        	   allowBlank : false,
	        	   blankText:'请输入登录名',
	        	   width: 250
	    }]},
	    
	    { layout : "form",
	           items : [{
	        	   xtype: 'textfield',
	        	   id: 'password', 
	        	   name: 'password', 
	        	   fieldLabel: '登录密码',
	        	   allowBlank : false,
	        	   blankText:'请输入登录密码',
	        	   width: 250
	}]},
	    

		 { layout : "form",
		           items : [{
					xtype: 'combo',
					id: 'belongorg',
					//name: 'belongorg', 
					fieldLabel: '所属机构', 
					store:new Ext.data.SimpleStore({fields:['id', 'text'],data:[[]]}), 
					displayField: 'id',
					valueField: 'text',
					hiddenName: 'belongorg',
		            editable:false, 
		            mode: 'local', 
		            triggerAction:'all', 
		            frame:true,
		            border:true,
		            width:250,
		            tpl: '<div id="treePanel1" style="height:180px;width:240px;"></div>', //html代码           
		            //autoWidth:true,
		            //autoHeight:true, 
		            emptyText:'清选择所属机构...',
		            resizable:true
		}]},
		
		 { layout : "form",
	           items : [{
	        	   xtype: 'textfield',
	        	   id: 'belongdept', 
	        	   name: 'belongdept', 
	        	   fieldLabel: '所属部门',
	        	   allowBlank : true,
	        	   blankText:'请输入所属部门',
	        	   width: 250
	}]},
		
		 { layout : "form",
	           items : [{
	        	   xtype: 'textfield',
	        	   id: 'companytel', 
	        	   name: 'companytel', 
	        	   fieldLabel: '办公电话',
	        	   width: 250
	     }]},
		
		{ layout : "form",
	           items : [{
	        	   xtype: 'textfield',
	        	   id: 'mobiletel', 
	        	   name: 'mobiletel', 
	        	   fieldLabel: '移动电话',
	        	   width: 250
	     }]},
	     
	     { layout : "form",
	           items : [{
	        	   xtype: 'textfield',
	        	   id: 'email', 
	        	   name: 'email', 
	        	   fieldLabel: 'Email',
	        	   width: 250
	     }]},
	     
	     
		]}]});

var tree1 = new Ext.tree.TreePanel
        ({ 
            animate:true,
            titleCollapse:true,
            root:root1,
            singleExpand:false,
            iconCls:"icon-tree",
            autoLoad:false,
            allowDomMove:true,
            frame:true,
            collapsible:false,
            collapsed:false,
            collapseFirst:true,
            border:false,
            listeners:{ 
            	render:function(tree){ 
            		tree.el.on('click',function(e){ 
					e.stopPropagation(); }) ;
				} 
			} 
});

var loader1=new Ext.tree.TreeLoader({dataUrl:'system/showOrgTree.do'});

var root1=new Ext.tree.AsyncTreeNode
        ({
         id:"0", 
         leaf:false,
         loader: loader1,
         text:"清远农商行总行",
         expandable:true,
         expanded:true 
     });         

tree1.setRootNode(root1);

var comboTree1 =  Ext.getCmp('belongorg');      
var orgCode1 = "";
comboTree1.on('expand',function(){tree1.render('treePanel1');});

var tree_click = function(node,e)
        {
			 e.stopEvent();   //非叶子节点则不触发
		     comboTree1.setValue(node.id);  //设置option值
		     comboTree1.setRawValue(node.text);
		     //comboTree.hiddenField.value = node.id;  
		 	comboTree1.collapse();   //隐藏option列表
		// 	alert(comboTree.value);
		// 	alert(comboTree.getValue());
		// 	alert(comboTree.getRawValue());
		 	//alert(comboTree.value);
		 	orgCode1 = comboTree1.value;
        };
tree1.on("click",tree_click);  		
		
var userStore = new Ext.data.Store({ 
	reader:new Ext.data.JsonReader({ },[
	{name:'userCode'}, 
	{name:'userName'}
	]) 
});

var userId = "";

		//新增客户表单
		transferForm = new Ext.form.FormPanel({ 
		id: 'transferForm', 
		width: 480, 
		height: 200, 
		//样式 
		bodyStyle: 'margin:auto;padding:auto;', 
		frame: true, 
		xtype: 'filedset', 
		labelWidth: 100, 
		items: 
		[ { xtype: 'fieldset',  
		collapsible: true, 
		autoHeight: true, 
		autoWidth: true, 
		items: 
		[ 
		 		{ layout : "form",
		           items : [{
		        	   xtype: 'combo',
						id: 'transferOrg',
						//name: 'belongorg', 
						fieldLabel: '转移至机构', 
						store:new Ext.data.SimpleStore({fields:['id', 'text'],data:[[]]}), 
						displayField: 'id',
						valueField: 'text',
						hiddenName: 'transferOrg',
			            editable:false, 
			            mode: 'local', 
			            triggerAction:'all', 
			            frame:true,
			            border:true,
			            width:250,
			            tpl: '<div id="treePanel2" style="height:180px;width:240px;"></div>', //html代码           
			            //autoWidth:true,
			            //autoHeight:true, 
			            emptyText:'清选择所属机构...',
			            resizable:true
		           }]},
		           
		           { layout : "form",
			           items : [{
			        	  xtype: 'combo', 
			        	  id : "transferUser",
			              store :userStore,
			              fieldLabel: '',
			              valueField : 'userCode',
			              displayField : 'userName',
			              fieldLabel: '转移至用户', 
			              emptyText : '请选择用户...',
			              editable: false,
			              typeAhead : true,
			              width: 250,
			              mode:'remote',  
			              triggerAction : 'all',
			              selectOnFocus : true,
			              hiddenName:'transferUser'
			     }]},
		]}]});
		


var tree2 = new Ext.tree.TreePanel
({ 
    animate:true,
    titleCollapse:true,
    root:root2,
    singleExpand:false,
    iconCls:"icon-tree",
    autoLoad:false,
    allowDomMove:true,
    frame:true,
    collapsible:false,
    collapsed:false,
    collapseFirst:true,
    border:false,
    listeners:{ 
    	render:function(tree1){ 
    		tree1.el.on('click',function(e){ 
			e.stopPropagation(); }) ;
		} 
	} 
});

var loader2=new Ext.tree.TreeLoader({dataUrl:'system/showOrgTree.do'});

var root2=new Ext.tree.AsyncTreeNode
({
 id:"0", 
 leaf:false,
 loader: loader2,
 text:"清远农商行总行",
 expandable:true,
 expanded:true 
});         

tree2.setRootNode(root2);

var comboTree2 =  Ext.getCmp('transferOrg');      
var orgCode2 = "";
comboTree2.on('expand',function(){tree2.render('treePanel2');});

var tree_click = function(node,e)
{
	 e.stopEvent();   //非叶子节点则不触发
     comboTree2.setValue(node.id);  //设置option值
     comboTree2.setRawValue(node.text);
     //comboTree.hiddenField.value = node.id;  
 	comboTree2.collapse();   //隐藏option列表
// 	alert(comboTree.value);
// 	alert(comboTree.getValue());
// 	alert(comboTree.getRawValue());
 	//alert(comboTree.value);
 	orgCode2 = comboTree2.value;
 	
 	
 	var transferUser = Ext.getCmp('transferUser');
		transferUser.clearValue(); //可以实现当下拉值变更时，清空之前下拉选项中的值   
//		 alert(combo.value);
		//alert(orgCode2);
		//alert(userId);
		userStore.proxy =new Ext.data.HttpProxy({
				url:'showUser.do?orgCode='+orgCode2,
				method:'GET'
		});
		userStore.load(); //加载下拉框的store   
};
tree2.on("click",tree_click);  
		
		//新增用户窗口 
		addWin = new Ext.Window({ 
		id: 'addWin', 
		title: '人员信息', 
		width: 500, 
		height: 300, 
		//背景遮罩 
		modal: true, 
		//重置大小 
		resizable: false, 
		//当关闭按钮被点击时执行的动作 
		closeAction: 'hide', 
		plain: true, 
		buttonAlign: 'right', 
		items:addForm, 
		buttons: 
		[  
		{ text: '保存', id: 'btnSubmit' } ,
		{ text: '关闭', handler: function() { Ext.getCmp('addWin').hide(); } }

		] 
		});
		
		//转移窗口 
		transferWin = new Ext.Window({ 
		id: 'transferWin', 
		title: '人员信息', 
		width: 500, 
		height: 220, 
		//背景遮罩 
		modal: true, 
		//重置大小 
		resizable: false, 
		//当关闭按钮被点击时执行的动作 
		closeAction: 'hide', 
		plain: true, 
		buttonAlign: 'right', 
		items:transferForm, 
		buttons: 
		[  
		{ text: '转移', id: 'btnSubmit1' } ,
		{ text: '关闭', handler: function() { Ext.getCmp('transferWin').hide(); } }
		] 
		});
		
		function startPD(){
			Ext.getCmp('addForm').form.reset();
			Ext.getCmp('password').setValue('0000000000');
			Ext.getCmp("addWin").buttons[0].handler = addFunction; 
			Ext.getCmp("addWin").show();
			
		}
		
		function transfer(){
			if (grid.getSelectionModel().getSelections()[0] == undefined) { 
				Ext.Msg.alert("提示", "请选中要查看的项！"); 
			}else{
				userId = grid.getSelectionModel().getSelections()[0].data.useId;
				
				//alert(grid.getSelectionModel().getSelections()[0].data.userId);
				
				Ext.getCmp('transferForm').form.reset();
				//Ext.getCmp('password').setValue('0000000000');
				Ext.getCmp("transferWin").buttons[0].handler = transferFunction; 
				Ext.getCmp("transferWin").show();
			}
		}

		function addFunction() {
			if(addForm.form.isValid()){
			 addForm.form.doAction('submit', { 
		                    url : 'system/addUser.do', 
		                    method : 'post',   
		                    params : { orgCodeValue: orgCode1},
		                    success : function() { 		                       
		                    	grid.store.reload();
		                    	 treePanel.root.reload();
		                    	Ext.Msg.alert('提示', '保存成功！'); 
		 
		                       }, 
		                        failure : function(form, action) { 
		                           Ext.Msg.alert('提示', '保存未成功！'); 
		                        } 
		                    });  
		                    }
		}


		function PDDetail(){
			if (grid.getSelectionModel().getSelections()[0] == undefined) { 
				Ext.Msg.alert("提示", "请选中要查看的项！"); 
				}
				else{
						var userId = grid.getSelectionModel().getSelections()[0].data.useId;
						//alert(userId);
					
					Ext.getCmp('addForm').form.reset(); 
					Ext.getCmp("addWin").buttons[0].handler = editAddressFunction; 
					
				Ext.Ajax.request({
				url:'system/getUser.do',
				params : { userId: grid.getSelectionModel().getSelections()[0].data.userId},
				method:'POST',
				   success:function(response){
				 var addJSON = Ext.util.JSON.decode(response.responseText);

				 	Ext.getCmp("addWin").show();
				  	Ext.getCmp("username").setValue(addJSON.username);
				  	Ext.getCmp("password").setValue(addJSON.password);
				  	Ext.getCmp("loginid").setValue(addJSON.loginid);
				   	Ext.getCmp("belongorg").setValue(addJSON.belongorg);
				   	Ext.getCmp("belongdept").setValue(addJSON.belongdept);
					Ext.getCmp("companytel").setValue(addJSON.companytel);
					Ext.getCmp("mobiletel").setValue(addJSON.moibletel);
					Ext.getCmp("email").setValue(addJSON.email);
				   	
				  },failure:function(){
				    Ext.MessageBox.alert("请求异常！");
				  }
				}); 
				}
		}
		
		//编辑
		function editAddressFunction(){
			
			var addForm = Ext.getCmp("addForm");
		if(addForm.form.isValid()){
			 addForm.form.doAction('submit', { 

		                    url : 'system/editUser.do', 
		                    params : { userId: grid.getSelectionModel().getSelections()[0].data.userId,orgCodeValue: orgCode1},
		                    method : 'post', 
		 
		                       
		                       success : function() { 

		                       
		                       grid.store.reload();
		                       treePanel.root.reload();
		                       Ext.Msg.alert('提示', '保存成功！'); 
		 
		                       }, 
		                        failure : function(form, action) { 

		                           Ext.Msg.alert('提示', '保存失败！'); 
		 
		                        } 
		                    }); 
		                    }
		}

		//移交
		function transferFunction(){
			
			var transferForm = Ext.getCmp("transferForm");
		if(transferForm.form.isValid()){
			transferForm.form.doAction('submit', { 

		                    url : 'system/transferUser.do', 
		                    params : { userId: grid.getSelectionModel().getSelections()[0].data.userId},
		                    method : 'post', 
		 
		                       
		                       success : function() { 

		                       
		                       grid.store.reload();
		                       treePanel.root.reload();
		                       Ext.Msg.alert('提示', '转移成功！'); 
		 
		                       }, 
		                        failure : function(form, action) { 

		                           Ext.Msg.alert('提示', '转移失败！'); 
		 
		                        } 
		                    }); 
		                    }
		}
		
		function deleteOrg(){
			if (grid.getSelectionModel().getSelections()[0] == undefined) { 
				Ext.Msg.alert("提示", "请选中要操作的项！"); 
			}
			else{
				
				var rows=grid.getSelectionModel().getSelections(); 
				//alert(selectedSerialNo);
				//window.location.href="rating/showHistoryPDList.do?custId="+selectedCustId;
				Ext.Msg.confirm("Confirm",'确实要删除所选中项吗？',function(bool){
					if(bool=='yes'){
						var selectedSerialNo = '';
					     for(var i=0;i <rows.length;i++){ 					      
					    	  selectedSerialNo = grid.getSelectionModel().getSelections()[i].data.userId; 					   
					    	  Ext.Ajax.request({
								  url:'system/deleteUser.do',
								  params : {userId : selectedSerialNo},
								  method:'POST',
								  success:function(){
								  // Ext.MessageBox.alert("提示","删除成功！");
								  //  grid.store.reload(); 
								   treePanel.root.reload();
								  },failure:function(){
								   // Ext.MessageBox.alert("提示", "删除失败！"); 
								  }
							});
					     }
					     
					     grid.store.reload();
					     Ext.MessageBox.alert("提示","删除成功！");
					     
						
						return true;
					}
					else{
						return false;	
					}
				}); 
				
			}
		}
		
		function initPassword(){
			if (grid.getSelectionModel().getSelections()[0] == undefined) { 
				Ext.Msg.alert("提示", "请选中要操作的项！"); 
			}
			else{
				var selectedSerialNo = grid.getSelectionModel().getSelections()[0].data.userId;
				//alert(selectedSerialNo);
				//window.location.href="rating/showHistoryPDList.do?custId="+selectedCustId;
				Ext.Msg.confirm("Confirm",'确实要初始化密码吗？',function(bool){
					if(bool=='yes'){
						Ext.Ajax.request({
							  url:'system/initUserPassword.do',
							  params : {userId : selectedSerialNo},
							  method:'POST',
							  success:function(){
							   Ext.MessageBox.alert("提示","初始化成功！");
							   grid.store.reload(); 
							   treePanel.root.reload();
							  },failure:function(){
							    Ext.MessageBox.alert("提示", "初始化失败！"); 
							  }
							});
						return true;
					}
					else{
						return false;	
					}
				}); 
				
			}
		}
		
		function associateRole(){
			if (grid.getSelectionModel().getSelections()[0] == undefined) { 
				Ext.Msg.alert("提示", "请选中要操作的项！"); 
			}
			else{
				window.location.href = "system/associateRole.do?userId="+grid.getSelectionModel().getSelections()[0].data.userId;
			}
		}
});